package org.dev.hi.hiui.tab.bottom;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import org.dev.hi.hiui.R;
import org.dev.hi.hiui.tab.common.IHiTabLayout;
import org.dev.hi.hiui.tab.common.OnTabSelectedListener;
import org.dev.hi.library.util.HiDisPlayUtils;
import org.dev.hi.library.util.HiViewUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public
/**
 * Author WenPing 
 * CreateTime 2021/3/9.
 * Description:
 */

class HITabBottomLayout extends FrameLayout implements IHiTabLayout<HiTabBottom, HiTabBottomInfo<?>> {

    private static final String TAG_TAB_BOTTOM = "TAG_TAB_BOTTOM";

    //tab集合实现监听
    private List<OnTabSelectedListener<HiTabBottomInfo<?>>> tabSelectedListeners = new ArrayList<>();

    //默认不透明度
    private float bottomAlpha = 1f;

    private HiTabBottomInfo<?> selectedInfo;

    private static float tabBottomHeight = 50;

    private String bottomLineColor = "#dfe0e1";

    //TabBottom的头部 线条高度
    private float bottomLineHeight = 0.5f;

    //tab的集合信息，通过set方法实现
    private List<HiTabBottomInfo<?>> infoList;


    public HITabBottomLayout(@NonNull Context context) {
        this(context, null);
    }

    public HITabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HITabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public HiTabBottom findTab(@NonNull HiTabBottomInfo<?> info) {
        ViewGroup ll = findViewWithTag(TAG_TAB_BOTTOM);
        for (int i = 0; i < ll.getChildCount(); i++) {
            View child = ll.getChildAt(i);
            if (child instanceof HiTabBottom) {
                HiTabBottom tabBottom = (HiTabBottom) child;
                if (tabBottom.getHiTabInfo() == info) {
                    return tabBottom;
                }
            }
        }
        return null;
    }

    @Override
    public void addTabSelectedChangeListener(OnTabSelectedListener<HiTabBottomInfo<?>> listener) {
        tabSelectedListeners.add(listener);
    }

    @Override
    public void defaultSelected(@NonNull HiTabBottomInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    private void onSelected(HiTabBottomInfo<?> nextInfo) {
        for (OnTabSelectedListener<HiTabBottomInfo<?>> listener : tabSelectedListeners) {
            listener.onTabSelectedChange(infoList.indexOf(nextInfo), selectedInfo, nextInfo);
        }
        this.selectedInfo = nextInfo;
    }

    @Override
    public void inflateInfo(@NonNull List<HiTabBottomInfo<?>> infoList) {
        if (infoList.isEmpty()) {
            return;
        }
        this.infoList = infoList;

        //移除之前添加的view
        for (int i = getChildCount() - 1; i > 0; i--) {
            removeViewAt(i);
        }
        selectedInfo = null;
        //相对布局添加一个全局的白色带透明度的背景
        addBackGround();

        //对tab的实例进行判断和移除,问题是下面这个泛型的逻辑会走吗？
        Iterator<OnTabSelectedListener<HiTabBottomInfo<?>>> iterator = tabSelectedListeners.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() instanceof HiTabBottom) {
                iterator.remove();
            }
        }
        //高度就是 tabBottom 高度
        int height = HiDisPlayUtils.dp2px(tabBottomHeight, getResources());
        FrameLayout ll = new FrameLayout(getContext());
        //下面把宽度进行 等分
        int width = HiDisPlayUtils.getDisplayWidthInPx(getContext()) / infoList.size();
        ll.setTag(TAG_TAB_BOTTOM);
        for (int i = 0; i < infoList.size(); i++) {
            final HiTabBottomInfo<?> info = infoList.get(i);
            LayoutParams params = new LayoutParams(width, height);
            params.gravity = Gravity.BOTTOM;
            //保持每个item之间的边距
            params.leftMargin = i * width;

            //有个问题，为什么可以添加？
            HiTabBottom tabBottom = new HiTabBottom(getContext());
            tabSelectedListeners.add(tabBottom);
            tabBottom.setHiTabInfo(info);

            ll.addView(tabBottom, params);
            tabBottom.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSelected(info);
                }
            });
        }
        LayoutParams flParams = new LayoutParams(LayoutParams.MATCH_PARENT
                , LayoutParams.WRAP_CONTENT);
        flParams.gravity = Gravity.BOTTOM;
        //配置底部的line，把line的高度算进去，实现贴合底部屏幕
        addBottomLine();
        addView(ll, flParams);
        fixContentView();
    }

    /**
     * 修复内容区域和底部之间的padding
     */
    private void fixContentView() {
        if (!(getChildAt(0) instanceof ViewGroup)) {
            return;
        }
        ViewGroup rootView = (ViewGroup) getChildAt(0);
        ViewGroup targetView = HiViewUtil.findViewByType(rootView, RecyclerView.class);
        if (targetView == null) {
            targetView = HiViewUtil.findViewByType(rootView, ScrollView.class);
        }
        if (targetView == null) {
            targetView = HiViewUtil.findViewByType(rootView, AbsListView.class);
        }

        clipBottomPadding(targetView);

//        if (targetView != null) {
//            targetView.setPadding(0, 0, 0, HiDisPlayUtils.dp2px(tabBottomHeight, getResources()));
//            targetView.setClipToPadding(false);
//        }
    }

    private void addBottomLine() {
        //创建一个一条线，这条线的底部距离是tab底部的高度 - 自身的高度
        View bottomLine = new View(getContext());
        bottomLine.setBackgroundColor(Color.parseColor(bottomLineColor));
        //设置line的高度，不能用wrapcontent
        LayoutParams bottomLayoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                HiDisPlayUtils.dp2px(bottomLineHeight));
        bottomLayoutParams.gravity = Gravity.BOTTOM;
        bottomLayoutParams.bottomMargin = HiDisPlayUtils
                .dp2px(tabBottomHeight - bottomLineHeight, getResources());
        addView(bottomLine, bottomLayoutParams);
        bottomLine.setAlpha(bottomAlpha);
    }

    private void addBackGround() {
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.hi_bottom_layout_bg, null);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                HiDisPlayUtils.dp2px(tabBottomHeight, getResources()));
        layoutParams.gravity = Gravity.BOTTOM;
        addView(view, layoutParams);
        view.setAlpha(bottomAlpha);
    }

    /**
     * 设置底部的padding，支持绘制
     * 下拉到底部的时候，不会被截取
     * @param targetView
     */
    public static void clipBottomPadding(ViewGroup targetView) {
        if (targetView != null) {
            targetView.setPadding(0, 0, 0, HiDisPlayUtils.dp2px(tabBottomHeight));
            //支持底部padding 可以绘制
            targetView.setClipToPadding(false);
        }
    }

    public void setBottomAlpha(float bottomAlpha) {
        this.bottomAlpha = bottomAlpha;
    }

    public void setSelectedInfo(HiTabBottomInfo<?> selectedInfo) {
        this.selectedInfo = selectedInfo;
    }

    public static void setTabBottomHeight(float tabBottomHeight) {
        HITabBottomLayout.tabBottomHeight = tabBottomHeight;
    }

    public void setBottomLineColor(String bottomLineColor) {
        this.bottomLineColor = bottomLineColor;
    }
}
